﻿using System;
using System.IO;
using System.Net;
using System.Linq;
using System.Text;
using System.Activities;
using System.Activities.Expressions;
using System.Activities.Presentation.PropertyEditing;
using System.Activities.Statements;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Markup;

namespace Vision.Core.ActivityComponents.Encryption.PGP
{
    /// <summary>
    /// 
    /// </summary>
    [ContentProperty("Body")]
    [Designer(typeof(PgpDecryptDesigner))]
    public class PgpDecrypt : NativeActivity
    {        
        /// <summary>
        /// 
        /// </summary>
        [Category("Input")]
        public InArgument<byte[]> PrivateKey { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [Category("Input")]
        public InArgument<string> PassPhrase { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [Category("Input")]
        public InArgument<byte[]> EncryptedFileData { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [Category("Output")]
        public OutArgument<byte[]> UnencryptedFileData { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [Category("Output")]
        public OutArgument<string> UnencryptedFileName { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [Browsable(false)]
        [DefaultValue(null)]
        public ActivityAction<byte[]> Body { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public PgpDecrypt()
        {
            this.Body = new ActivityAction<byte[]>()
            {
                Argument = new DelegateInArgument<byte[]>()
                {
                    Name = "decryptedFileData"
                }
            };
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        protected override void Execute(NativeActivityContext context)
        {
            using (MemoryStream encryptedFileStream = new MemoryStream(this.EncryptedFileData.Get(context)))
            using (MemoryStream privateKeyStream = new MemoryStream(this.PrivateKey.Get(context))){
                byte[] fileData = new byte[0];
                string fileName = string.Empty;

                PGPWrapper.DecryptStream(encryptedFileStream, privateKeyStream, this.PassPhrase.Get(context), out fileData, out fileName);

                this.UnencryptedFileData.Set(context, fileData);
                this.UnencryptedFileName.Set(context, fileName);

                context.ScheduleAction<byte[]>(this.Body, fileData);
            }
        }
    }
}
